package com.avcdata.national.utils;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class FormatNum {
    /***
     * 将Json中的数字全部保留两位小数
     *
     * @param str
     * @return
     */
    public static String obj2Fixed(String str) {

        if ("{".equals(str.toCharArray()[0])) {
            Map<String, String> maps = new HashMap<String, String>();
            Map<String, String> map = new Gson().fromJson(str, Map.class);
            for (Entry<String, String> e : map.entrySet()) {
                if (e.getValue().startsWith("[") || e.getValue().startsWith("{")) {
                    obj2Fixed(e.getValue());
                } else {
                    String str1 = "";
                    try {
                        str1 = MyUtils.format2(Double.parseDouble(e.getValue()));
                    } catch (Exception e2) {
                        str1 = e.getValue();
                    }
                    maps.put(e.getKey(), e.getValue());
                }
            }
            return new Gson().toJson(maps);
        } else if ("[".equals(str.toCharArray()[0])) {
            List<String> results = new ArrayList<String>();
            List<String> lists = new Gson().fromJson(str, List.class);
            for (String s : lists) {
                if (s.startsWith("[") || s.startsWith("{")) {
                    obj2Fixed(s);
                } else {
                    String str1 = "";
                    try {
                        str1 = MyUtils.format2(Double.parseDouble(s));
                    } catch (Exception e2) {
                        str1 = s;
                    }
                    results.add(s);
                }
            }
            return new Gson().toJson(results);
        } else {
            return str;
        }
    }

}
